import pyautogui
import time
import pyperclip
from tkinter import messagebox, Tk
from datetime import datetime

# 配置参数
WINDOW_WAIT_TIME = 3
MAX_ATTEMPTS = 10
HISTORY_FILE = "save_history.log"

class EnhancedAutoSaver:
    def __init__(self):
        self.processed_count = 0
        self.history = []

    def capture_filename(self):
        """获取当前保存的文件名"""
        try:
            pyautogui.hotkey("ctrl", "c")  # 复制文件名
            time.sleep(0.3)
            filename = pyperclip.paste().strip()
            return filename if filename else "unknown"
        except Exception:
            return "unknown"

    def handle_overwrite(self):
        """智能处理文件覆盖提示"""
        try:
            # 检测覆盖确认对话框
            if pyautogui.locateOnScreen('overwrite_dialog.png'):
                pyautogui.press("enter")
        except Exception:
            pass

    def save_current_file(self):
        """执行保存操作并记录历史"""
        pyautogui.hotkey("ctrl", "s")
        time.sleep(0.8)
        
        filename = self.capture_filename()
        pyautogui.press("enter")
        time.sleep(0.5)

        # 处理可能的覆盖提示
        if self.processed_count > 0:
            self.handle_overwrite()

        # 记录保存信息
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.history.append({
            "filename": filename,
            "timestamp": timestamp
        })
        self.processed_count += 1

    def save_history_file(self):
        """保存历史记录到文件"""
        try:
            with open(HISTORY_FILE, "a", encoding="utf-8") as f:
                for record in self.history:
                    f.write(f"[{record['timestamp']}] {record['filename']}\n")
        except Exception as e:
            messagebox.showerror("错误", f"保存历史文件失败: {str(e)}")

    def main_process(self):
        """主控制流程"""
        messagebox.showinfo("提示", "请切换到图片查看窗口后点击确定\n"
                              f"程序将在{WINDOW_WAIT_TIME}秒后开始运行")
        time.sleep(WINDOW_WAIT_TIME)

        for _ in range(MAX_ATTEMPTS):
            try:
                self.save_current_file()
                pyautogui.press("left")
                time.sleep(0.8)
            except Exception as e:
                messagebox.showerror("错误", f"操作中断: {str(e)}")
                break

        self.save_history_file()
        messagebox.showinfo("完成", 
            f"成功处理 {self.processed_count} 个文件\n历史记录已保存到 {HISTORY_FILE}")

if __name__ == "__main__":
    try:
        root = Tk()
        root.withdraw()
        saver = EnhancedAutoSaver()
        saver.main_process()
        root.destroy()
    except Exception as e:
        messagebox.showerror("错误", f"程序异常: {str(e)}")
